package com.uit.trip_;

import com.facebook.FacebookActivity;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.widget.LoginFragment;
import com.uit.trip_.R;
import com.uit.trip_.fragments.HomeFragment;
import com.uit.trip_.fragments.SplashFragment;

import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

public class MainActivity extends FacebookActivity {

	private static final int SPLASH = 0;
	private static final int SELECTION = 1;
	private static final int SETTINGS = 2;
	private static final int FRAGMENT_COUNT = SETTINGS + 1;
	private static final String FRAGMENT_PREFIX = "fragment";

	private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
	private MenuItem settings;
	private boolean restoredFragment = false;
	private boolean isResumed = false;
	private boolean isStartNew = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		for (int i = 0; i < fragments.length; i++) {
			restoreFragment(savedInstanceState, i);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		isResumed = true;
		Log.i("duongnx", "onResumedMain");
	}

	@Override
	public void onPause() {
		super.onPause();
		isResumed = false;
		LocalActivityManager m = new LocalActivityManager(this, false);
		m.dispatchPause(isFinishing());
	}

	@Override
	protected void onResumeFragments() {
		super.onResumeFragments();
		Session session = Session.getActiveSession();
		if (session == null || session.getState().isClosed()) {
			session = new Session(this);
			Session.setActiveSession(session);
		}

		FragmentManager manager = getSupportFragmentManager();

		if (restoredFragment) {
			return;
		}

		// If we already have a valid token, then we can just open the session
		// silently,
		// otherwise present the splash screen and ask the user to login.
		if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
			// no need to add any fragments here since it will be handled in
			// onSessionStateChange
			session.openForRead(this);
		} else if (session.isOpened()) {
			// if the session is already open, try to show the selection
			// fragment
			Fragment fragment = manager.findFragmentById(R.id.body_frame);
			if (!(fragment instanceof HomeFragment)) {
				manager.beginTransaction()
						.replace(R.id.body_frame, fragments[SELECTION])
						.commit();
			}

			Log.i("duongnx", "resume:no start");
			// Chuyen views
			if (isStartNew) {
				Log.i("duongnx", "start tab activi:onreume");
				startActivityForResult(
						new Intent(this, TripMainActivity.class), 100);

			}

		} else {
			FragmentTransaction transaction = manager.beginTransaction();
			transaction.replace(R.id.body_frame, fragments[SPLASH]).commit();
			isStartNew = true;
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		FragmentManager manager = getSupportFragmentManager();
		Fragment currentFragment = manager.findFragmentById(R.id.body_frame);
		// only add the menu when the selection fragment is showing
		if (currentFragment == fragments[SELECTION]) {
			if (menu.size() == 0) {
				settings = menu.add(R.string.settings);
			}
			return true;
		} else {
			menu.clear();
			settings = null;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.equals(settings)) {
			FragmentManager manager = getSupportFragmentManager();
			FragmentTransaction transaction = manager.beginTransaction();
			transaction.add(R.id.body_frame, fragments[SETTINGS])
					.addToBackStack(null).commit();
			return true;
		}

		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		FragmentManager manager = getSupportFragmentManager();
		// Since we're only adding one Fragment at a time, we can only save one.
		Fragment f = manager.findFragmentById(R.id.body_frame);
		for (int i = 0; i < fragments.length; i++) {
			if (fragments[i] == f) {
				manager.putFragment(outState, getBundleKey(i), fragments[i]);
			}
		}
	}

	@Override
	protected void onSessionStateChange(SessionState state, Exception exception) {
		if (isResumed) {
			FragmentManager manager = getSupportFragmentManager();
			int backStackSize = manager.getBackStackEntryCount();
			for (int i = 0; i < backStackSize; i++) {
				manager.popBackStack();
			}
			if (state.isOpened()) {
				if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
					// ((SelectionFragment)
					// fragments[SELECTION]).tokenUpdated();
				} else {
					FragmentTransaction transaction = manager
							.beginTransaction();
					transaction.replace(R.id.body_frame, fragments[SELECTION])
							.commit();
					Log.i("duongnx", "thay the sflash");
					if (isStartNew) {
						startActivityForResult(new Intent(this,
								TripMainActivity.class), 100);
						Log.i("duongnx", "start tab activi");
					}
				}
			} else if (state.isClosed()) {
				FragmentTransaction transaction = manager.beginTransaction();
				transaction.replace(R.id.body_frame, fragments[SPLASH])
						.commit();
				isStartNew = true;
				Log.i("duongnx", "close section");
			}
		}
	}

	/**
	 * Returns the key to be used when saving a Fragment to a Bundle.
	 * 
	 * @param index
	 *            the index of the Fragment in the fragments array
	 * @return the key to be used
	 */
	private String getBundleKey(int index) {
		return FRAGMENT_PREFIX + Integer.toString(index);
	}

	/**
	 * Restore fragments from the bundle. If a necessary Fragment cannot be
	 * found in the bundle, a new instance will be created.
	 * 
	 * @param savedInstanceState
	 * @param fragmentIndex
	 */
	private void restoreFragment(Bundle savedInstanceState, int fragmentIndex) {
		Fragment fragment = null;
		if (savedInstanceState != null) {
			FragmentManager manager = getSupportFragmentManager();
			fragment = manager.getFragment(savedInstanceState,
					getBundleKey(fragmentIndex));
		}
		if (fragment != null) {
			fragments[fragmentIndex] = fragment;
			restoredFragment = true;
		} else {
			switch (fragmentIndex) {
			case SPLASH:
				fragments[SPLASH] = new SplashFragment();
				break;
			case SELECTION:
				fragments[SELECTION] = new LoginFragment();
				break;
			case SETTINGS:
				fragments[SETTINGS] = new LoginFragment();
				break;
			default:

				break;
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("duongnx", "onActivityResultMain:requestcode:" + requestCode
				+ ":" + resultCode);
		if (resultCode == RESULT_OK && requestCode == 100) {
			isStartNew = false;
		}

	}
}
